package at.fhhagenberg.mcm09.elevator.control;

import java.util.Queue;

import at.fhhagenberg.mcm09.elevator.model.StopRequest;

public class ResortAlgorithm implements IAlgorithm{

	@Override
	public int getTargetFloor(Queue<StopRequest> q, int _curFloor) {
		
		
		int s = q.size();
		StopRequest[] qa = new StopRequest[s];
		qa = q.toArray(qa);
		int nextfloor = q.peek().getTargetFloor();
		int committedFloor = nextfloor;
		
		//now try to find intermediate targets
		if(_curFloor > nextfloor){ //direction is downward
			for(int i=1; i<s; i++){
				if(qa[i].getTargetFloor()  < _curFloor && 
				   qa[i].getTargetFloor() > committedFloor){
					committedFloor = qa[i].getTargetFloor();
				}
			}
		}
		
		else if(_curFloor < nextfloor){
			for(int i=1; i<s; i++){
				if(qa[i].getTargetFloor() > _curFloor && 
				   qa[i].getTargetFloor()< committedFloor){
					committedFloor = qa[i].getTargetFloor();
				}
			}
		}
		
		
		return committedFloor;
	}



}
